/******************************
Copyright (c) 2009, Avanade
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Avanade nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
******************************/


// Set these variables to change beginning map location
var beginLatitude = 47.6;
var beginLongitude = -122.33;
var beginZoom = 10;

// Url for accessing data from database
var pinServiceUrl = "returnresults.php";

// Global variable to initialize VEMap in
var map = null;
// Global variable to track current pinId
var pinid = 0;
// Should we render the map now or wait for call back
var waitingForCallback = false;

// To hold values for call back function
var tmpTitle = null;
var tmpDescription = null;

// Initialize map
// mapDivName - Div container for map
function GetMap(mapDivName) {
    map = new VEMap(mapDivName);
    map.LoadMap(new VELatLong(beginLatitude, beginLongitude), beginZoom, 'h', false);
    map.SetZoomLevel(beginZoom);
    map.AttachEvent("onchangeview", MapChangeHandler);

    LoadPushPins();
}

// Add Pushpin at desired latitude & longitude
// Title - Title of Pushpin
// Description - Description to set on Pushpin
// latLon - VELatLong object of location to set PushPin
function AddPushpin(title, description, latLon) {
    var shape = new VEShape(VEShapeType.Pushpin, latLon);
    shape.SetTitle(title);
    shape.SetDescription(description);
    pinid++;
    map.AddShape(shape);
}

// Try to find this location and add a pushpin if successfull
// Location - string value of location to add to map
function FindAndAddPin(title, description, location) {
    if(title == null || description == null || location == null || 
	   title.length == 0 || description.length == 0 || location.length == 0) {
	    alert('Title, Description & Location are all required fields');
    }
    else {
        try {
    	    tmpTitle = title;
    	    tmpDescription = description;
            map.Find(null, location,null,null,0,1,false,false,true,true,MapFindCallback);
            waitingForCallback = true;
        }
        catch (e) {
            alert(e.message);
            waitingForCallback = false; 
        }
    }
}

// Call back function for when a map location is found
function MapFindCallback(layer, resultsArray, places, hasMore, veErrorMessage)
{
	if(places != null)
	{
	    var latLon = places[0].LatLong;
	    
	    SavePushPin(tmpTitle, tmpDescription, latLon.Latitude, latLon.Longitude);
	    tmpTitle = null;
	    tmpDescription = null;
    }
}

// Repopulates maps with push pins on map change events
function MapChangeHandler(e) {
    if(!waitingForCallback)
    {
        LoadPushPins();
    }
}

// Load the current map with push pins
function LoadPushPins() {
    view = map.GetMapView();
    topleft = view.TopLeftLatLong;
    bottomright = view.BottomRightLatLong;
    
    $.getJSON(pinServiceUrl, { tlLat: topleft.Latitude, tlLong: topleft.Longitude, brLat: bottomright.Latitude , brLong: bottomright.Longitude}, GetPinsCallback);
}

// Call back from JSON getPins command.  Parse JSON response and adds pins to map.
function GetPinsCallback(jsonData) {
	map.Clear();
    $.each(jsonData, function(i, item) {
        AddPushpin(item.title, item.description, new VELatLong(item.latitude, item.longitude));
    });
}

// Save the current push pin
function SavePushPin(title, description, latitude, longitude) {
    waitingForCallback = false; 

    $.post(pinServiceUrl, { title: title, description: description, latitude: latitude, longitude: longitude }, LoadPushPins);
}